package com.gs.api.util.http;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.*;
import java.util.ArrayList;

/**
 * @author guoyunfei on 2021/7/5 20:52
 * @className HttpUtilDown
 * @description TODO
 * @Version 1.0
 */
public class HttpUtilDown {


    /**
     * 传入要下载的图片的url列表，将url所对应的图片下载到本地
     */
    public static void downloadPicture(Object urlString, String imagePath, String name) throws RuntimeException {

        File file = new File(imagePath);
        if (!file.exists()) {
            file.mkdirs();
        }

        if (urlString == null) {
            throw new RuntimeException("下载图片地址为空");
        }
        URL url = null;
        try {
            url = new URL(urlString.toString());

            DataInputStream dataInputStream = new DataInputStream(url.openStream());
            FileOutputStream fileOutputStream = new FileOutputStream(new File(imagePath + File.separator + name));

            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                fileOutputStream.write(buffer, 0, length);
            }

            dataInputStream.close();
            fileOutputStream.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
            throw new RuntimeException("下载、保存图片失败" + urlString);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("保存图片失败" + urlString);
        }
    }

    /**
     * 传入要下载的图片的url列表，将url所对应的图片下载到本地
     *
     * @param urlList
     */
    private void downloadPicture(ArrayList<String> urlList,String path) {
        URL url = null;
        int imageNumber = 100;

        for (String urlString : urlList) {
            try {
                url = new URL(urlString);
                DataInputStream dataInputStream = new DataInputStream(url.openStream());
                String imageName = path + imageNumber + ".jpg";
                FileOutputStream fileOutputStream = new FileOutputStream(new File(imageName));

                byte[] buffer = new byte[1024];
                int length;

                while ((length = dataInputStream.read(buffer)) > 0) {
                    fileOutputStream.write(buffer, 0, length);
                }

                dataInputStream.close();
                fileOutputStream.close();
                imageNumber++;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 下载网络文件
     * @param response
     * @param downUrl
     * @param fileName
     */
    public static void download(HttpServletResponse response,String downUrl,String fileName){
        try {
            URL url = new URL(downUrl);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(3*1000);
            //防止屏蔽程序抓取而返回403错误
            conn.addRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36");

            //得到输入流
            InputStream inputStream = conn.getInputStream();
            //获取自己数组
            byte[] bs = readInputStream(inputStream);
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            BufferedOutputStream output = null;
            BufferedInputStream input = null;
            try {
                output = new BufferedOutputStream(response.getOutputStream());

                //告诉浏览器输出内容为流
                response.setContentType("application/octet-stream");
                //Content-Disposition中指定的类型是文件的扩展名，并且弹出的下载对话框中的文件类型图片是按照文件的扩展名显示的，点保存后，文件以filename的值命名，保存类型以Content中设置的为准。注意：在设置Content-Disposition头字段之前，一定要设置Content-Type头字段。
                //把文件名按UTF-8取出并按ISO8859-1编码，保证弹出窗口中的文件名中文不乱码，中文不要太多，最多支持17个中文，因为header有150个字节限制。
                // modify by lijianyuan 20170122 编码文件格式
                response.addHeader("Content-Disposition", "attachment;filename="+encodeFileName(fileName));

                output.write(bs);
                response.flushBuffer();
            } catch (Exception e) {
                System.out.println("Download log file error："+e);
            } // 用户可能取消了下载
            finally {
                if (input != null)
                    try {
                        input.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                if (output != null)
                    try {
                        output.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 从输入流中获取字节数组
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    /**
     * add by lijianyuan 20170122 编码文件格式
     * 转换下载文件名字的编码
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String encodeFileName(String fileName){
        String retFileName = StringUtils.trim(fileName);
        if(null == retFileName){
            return "";
        }
        try{
            retFileName = URLEncoder.encode(retFileName,"UTF-8");
            retFileName = StringUtils.replace(retFileName, "+","%20");
            if(retFileName.length() > 150){
                retFileName = new String(retFileName.getBytes("GB2312"),"ISO8859-1");
                retFileName = StringUtils.replace(retFileName, " ","%20");
            }
        }catch(UnsupportedEncodingException  e){

        }

        return retFileName;

    }

}
